package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Override
    public String getOpenid(String code) {
        Map<String, Object> dataMap = getStringObjectMap();
        dataMap.put("js_code", code);
        dataMap.put("grant_type", "authorization_code");
        String res = HttpUtil.get(REQUEST_URL, dataMap);
        JSONObject bean = JSONUtil.toBean(res, JSONObject.class);
        String openid = bean.getStr("openid");
        if (ObjectUtil.isEmpty(openid)) {
            throw new BaseException("获取openid失败！");
        }
        return openid;
    }


    @Override
    public String getPhone(String code) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", code);
        HttpResponse response = HttpUtil.createPost(PHONE_REQUEST_URL + getAccessToken()).body(JSONUtil.toJsonStr(dataMap)).execute();
        String res = response.body();
        JSONObject bean = JSONUtil.toBean(res, JSONObject.class);
        Object phone = bean.getByPath("phone_info.purePhoneNumber");
        if (ObjectUtil.isEmpty(phone)) {
            throw new BaseException("获取手机号失败！");
        }
        return phone.toString();
    }

    private String getAccessToken() {
        Map<String, Object> dataMap = getStringObjectMap();
        dataMap.put("grant_type", "client_credential");
        String res = HttpUtil.get(TOKEN_URL, dataMap);
        JSONObject bean = JSONUtil.toBean(res, JSONObject.class);
        String token = bean.getStr("access_token");
        return token;
    }

    private @NotNull Map<String, Object> getStringObjectMap() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("appid", appid);
        dataMap.put("secret", secret);
        return dataMap;
    }
}
